/**
 * @author MADSTONE_L
 */
Ext.onReady(function() {
	Date.patterns = {
		ISO8601Long : "Y-m-d H:i:s",
		ISO8601Short : "Y-m-d",
		ShortDate : "n/j/Y",
		LongDate : "l, F d, Y",
		FullDateTime : "l, F d, Y g:i:s A",
		MonthDay : "F d",
		ShortTime : "g:i A",
		LongTime : "g:i:s A",
		SortableDateTime : "Y-m-d\\TH:i:s",
		UniversalSortableDateTime : "Y-m-d H:i:sO",
		YearMonth : "F, Y"
	};

	// Ext.apply(Ext.data.reader.Json.prototype, {
	// type: 'json',
	// root: 'root',
	// idProperty: 'id',
	// totalProperty: 'total',
	// successProperty: 'success',
	// messageProperty: 'message'
	// });

	Ext.apply(Ext.grid.Panel.prototype, {

				/**
				 * 验证Grid的选择
				 * 
				 * @param {Boolean}
				 *            showMsg 当没有选择项时，是否提示
				 * @return {Boolean}
				 */
				checkSelect : function(showMsg) {
					var sm = this.getSelectionModel();
					var s = sm.getSelected();
					if (!s) {

						if (Ext.isBoolean(showMsg) && showMsg) {
							Ext.Msg.showNotSelected();
						} else if (!Ext.isBoolean(showMsg)
								&& !Ext.isEmpty(showMsg)) {
							Ext.Msg.showWarning(showMsg);
						}
						return false;
					}
					// 判断是否为单选
					return sm.singleSelect ? s : sm.getSelections();
				},
				find : function(btn) {
					var me = this;
					var _v = me.getTbarValues();
					if (!_v)
						return false;
					var store = me.getStore();
					// var proxy = store.getProxy();
					// Ext.applyIf(_v, defaults);
					Ext.apply(store.proxy.extraParams, _v);
					// Ext.apply(store.proxy.extraParams, {
					// start : 0,
					// page : 1,
					// limit : store.pageSize
					// });
					// store.load();
					store.currentPage = 1;
					store.load({
								params : {
									start : 0,
									page : 1,
									limit : store.pageSize
								}
							});
				},
				clear : function() {
					var tbar = this.getDockedItems('toolbar[dock="top"]')
					var fields = tbar[0].query('field');
					Ext.each(fields, function(v, i, a) {
								if (!v.disabled && !v.hidden && !v.readOnly)
									v.reset();
							});
					Ext.each(fields, function(v, i, a) {
								if (!v.disabled && !v.hidden && !v.readOnly) {
									v.focus(true, true);
									return false;
								}
							});

				},
				getTbarValues : function() {
					var me = this;
					var store = me.getStore();
					var tbar = this.getDockedItems('toolbar[dock="top"]')
					var fields = tbar[0].query('field');
					if (fields.length == 0) {
						Ext.Msg.showError('没有查询条件，请确定！');
						return false;
					}
					var params = '{';
					var value, valid;
					Ext.each(fields, function(v, i, a) {
								if (!v.isValid()) {
									Ext.Msg.showWarning('请将资料填写完整！',
											function() {
												this.focus(true, 200);
											}, v);
									valid = false;
									return valid;
								}
								value = Ext.isFunction(v.getValue2) ? v
										.getValue2() : v.getValue();
								if (v.getXType() == 'datefield'
										&& Ext.isDate(value))
									value = v.formatDate(value);

								if (Ext.isEmpty(value))
									value = '';

								params += '"' + v.getName() + '":"'
										+ value.toString().trim() + '",'
							});
					if (valid === false)
						return false;

					return Ext.decode(params.substring(0, params.length - 1)
							+ "}");

				}

			});

	Ext.apply(Ext.form.DateField.prototype, {
				format : "Y-m-d",
				getValue2 : function() {
					var d = this.getValue();
					if (Ext.isDate(d)) {
						// 兼容原来的addValue
						if (Ext.isNumber(this.addValue)
								|| Ext.isNumber(this.addDay))
							d = Ext.Date.add(d, Ext.Date.DAY, this.addValue
											|| this.addDay);
						if (Ext.isNumber(this.addHour))
							d = Ext.Date.add(d, Ext.Date.HOUR, this.addHour);
						if (Ext.isNumber(this.addMilli))
							d = Ext.Date.add(d, Ext.Date.MILLI, this.addMilli);
						if (Ext.isNumber(this.addMinute))
							d = Ext.Date
									.add(d, Ext.Date.MINUTE, this.addMinute);
						if (Ext.isNumber(this.addMonth))
							d = Ext.Date.add(d, Ext.Date.MONTH, this.addMonth);
						if (Ext.isNumber(this.addSecond))
							d = Ext.Date
									.add(d, Ext.Date.SECOND, this.addSecond);
						if (Ext.isNumber(this.addYear))
							d = Ext.Date.add(d, Ext.Date.YEAR, this.addYear);
					}
					return d;
				}
			});

	// 扩展Msg提示框
	if (Ext.Msg)
		Ext.applyIf(Ext.Msg, {
					showError : function(msg, fn, scope, title, width, btn) {
						this.show({
									title : title || '错误提示',
									msg : msg,
									buttons : btn || this.OK,
									fn : fn,
									animEl : Sys.animEl,
									scope : scope,
									icon : this.ERROR,
									minWidth : width || this.minWidth
								});
						return this;
					},
					showWarning : function(msg, fn, scope, title, width, btn) {
						this.show({
									title : title || '操作警告',
									msg : msg,
									buttons : btn || this.OK,
									fn : fn,
									animEl : Sys.animEl,
									scope : scope,
									icon : this.WARNING,
									minWidth : width || this.minWidth
								});
						return this;
					},
					showInfo : function(msg, fn, scope, title, width, btn) {
						this.show({
									title : title || '操作提示',
									msg : msg,
									buttons : btn || this.OK,
									fn : fn,
									animEl : Sys.animEl,
									scope : scope,
									icon : this.INFO,
									minWidth : width || this.minWidth
								});
						return this;
					},
					showNotSelected : function() {
						this.showWarning('您没有选择任何可操作项，请确认！');
					},
					showNotExistModel : function() {
						this.showError('该模块尚未开放，或您无权访问！');
					},
					showFError : function(f, a, fn, scope) {
						switch (a.failureType) {
							case Ext.form.Action.CLIENT_INVALID :
								Ext.Msg.showWarning('请将资料填写完整！');
								break;
							case Ext.form.Action.CONNECT_FAILURE :
								Ext.Msg.showError('服务器错误，错误号：'
												+ a.response.status, fn, scope);
								break;
							case Ext.form.Action.SERVER_INVALID :
								Ext.Msg.showError(a.result.msg, fn, scope);
								break;
							case Ext.form.Action.LOAD_FAILURE : // 服务端response的data属性没有返回任何字段的值得时候返回的错误类型
								Ext.Msg.showError('服务器没有返回数据！');
								break;
						}
					},
					showRError : function(r, o, msg, fn, scope) {
						Ext.Msg.showError((msg || '操作') + '失败，错误号：' + r.status
										+ '。请重试，或与管理员联系！', fn, scope);
					}
				});
	Ext.util.Format.comboRenderer = function(combo) {
		return function(value) {
			// debugger;
			var record = combo.findRecord(combo.valueField, value);
			return record
					? record.get(combo.displayField)
					: combo.valueNotFoundText;
		}
	}
	/**
	 * 扩展VType的验证种类
	 */
	Ext.apply(Ext.form.VTypes, {
		/**
		 * 两个日期范围的验证
		 * 
		 * @param {}
		 *            val
		 * @param {}
		 *            field
		 * @return {Boolean}
		 */
		daterange : function(val, field) {
			var date = field.parseDate(val);
			if (!date) {
				return false;
			}
			if (field.startDateField
					&& (!this.dateRangeMax || (date.getTime() != this.dateRangeMax
							.getTime()))) {
				var start = Ext.getCmp(field.startDateField);
				start.setMaxValue(date);
				if (!Ext.isEmpty(start.getValue()))
					start.validate();
				this.dateRangeMax = date;
			} else if (field.endDateField
					&& (!this.dateRangeMin || (date.getTime() != this.dateRangeMin
							.getTime()))) {
				var end = Ext.getCmp(field.endDateField);
				end.setMinValue(date);
				if (!Ext.isEmpty(end.getValue()))
					end.validate();
				this.dateRangeMin = date;
			}
			/*
			 * Always return true since we're only using this vtype to set the
			 * min/max allowed values (these are tested for after the vtype
			 * test)
			 */
			return true;
		},
		postalcode : function(val, field) {
			return /^[1-9]\d{5}(?!\d)$/.test(val);
		},
		postalcodeText : '请正确输入6位邮政编码',
		phone : function(val, field) {
			// 支持手机号码，3-4位区号，7-8位直播号码，1－4位分机号
			return /^(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/
					.test(val);
		},
		phoneText : '请正确输入电话号码，如12345678901、12345678、1234-12345678-1234',
		mobele : function(val, field) {
			return /^1[0-9]{10}$/.test(val);
		},
		mobeleText : '请正确输入11位手机号码',
		chinese : function(val, field) {
			return /^[\u4E00-\u9Fa5]+$/.test(val);
		},
		chineseText : '请输入汉字',
		cnusername : function(val, field) {
			return /^[\u4E00-\u9Fa5]([a-zA-Z0-9]|[\u4E00-\u9Fa5]){1,9}$/
					.test(val);
		},
		cnusernameText : '请以中文汉字开头,2-10位,其中允许字母数字',
		signusername : function(val, field) {
			return /^[a-zA-Z][a-zA-Z0-9_]{3,17}$/.test(val);
		},
		signusernameText : '请以字母开头，允许4-18位，允许字母数字下划线',
		ip : function(val, field) {
			return /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
					.test(val);
		},
		ipText : '请正确输入IP地址',
		pwdStrength : function(val, field) {
			return /^[a-zA-Z0-9_-]{6,18}$/.test(val);
		},
		pwdStrengthText : '只能输入字母、数字、“-”、“_”，6-18位',
		idnumber : function(val, field) {
			return /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/
					.test(val)
					|| /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(?:\d|x|X)$/
							.test(val);
		},
		idnumberText : '请正确输入16位或18位大陆身份证号码',
		password : function(val, field) {
			if (field.initialPassField) {
				var pwd = Ext.getCmp(field.initialPassField);
				return (val == pwd.getValue());
			}
			return true;
		},
		passwordText : '两次密码输入不一致'
	});
});